//
//  FamilyManageVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/6/28.
//  Copyright © 2020 tym. All rights reserved.
//

#import "FamilyManageVC.h"
#import "MyFamilyApplyCell.h"
#import "Sizes.h"
#import "YoukeUserVC.h"
#import "UserTool.h"
#import "FamilyModel.h"
#import "UserService.h"
#import "UIimage+Extends.h"
#import "HXPhotoView.h"
#import "YPVideoPickerViewController.h"
#import "UIImageView+YPImage.h"
#import "CreateNewHomeViewController.h"
#import "JoinHomeViewController.h"
#import "AddFamilyView.h"
#import "FamilyOptionView.h"
#import "FamilyDescVC.h"
#import "ChangeFamilyVC.h"
#import "UserTool.h"
#import "UserModel.h"
#import "FamilyService.h"
#import "FamilyNameVC.h"
#import "FamilyDetailVC.h"
#import "BlacklistVC.h"
#import "FamilymemberVC.h"
#import "Colors.h"
#import "WHToast.h"
#import "ShowAlertView.h"
#import "Fonts.h"
#import "TYMButton.h"
#import "TYMBaseTableViewCell.h"
#import "FamilyManageTwoCell.h"
#import "FamilyManageOneCell.h"
#import "GroupShadowTableView.h"
#import "FamilyManageThreeCell.h"
#import "HXPhotoManager.h"

@interface FamilyManageVC ()<GroupShadowTableViewDelegate, GroupShadowTableViewDataSource,HXPhotoViewControllerDelegate>

@property (nonatomic, strong) GroupShadowTableView *tableView;

@property (strong, nonatomic) HXPhotoManager *manager;//相册manager

@property(nonatomic,strong) NSMutableArray *oneArray;
@property(nonatomic,strong) NSMutableArray *twoArray;
@property(nonatomic,strong) NSMutableArray *threeArray;
@property(nonatomic,assign) NSInteger threeIndex;
@property(nonatomic,weak) IBOutlet UIButton *optionBtn;

@property(nonatomic,strong) FamilyService *familyService;

@property(nonatomic,assign) NSInteger optionRow; //将要操作的申请单元格

@end

@implementation FamilyManageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.threeIndex = 0;
    
    [self addBackBtnFunc];
    [self addTitle:@"家庭管理"];
    [self addRightBtnImage:@"icon_home5"];
    [self setTable];
    
}

- (void)setTable {
    self.tableView = [[GroupShadowTableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-NavigateonHeight-74-SafeBottomMargin) style:UITableViewStyleGrouped];
    self.tableView.groupShadowDelegate = self;
    self.tableView.groupShadowDataSource = self;
    self.tableView.backgroundColor = viewBGColor;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.01)];
    self.tableView.sectionFooterHeight = 0;
    _tableView.showSeparator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];

    if ([UserTool getCurrentFamily].familyRole == 1) {
        [self.optionBtn setTitle:@"删除并退出家庭" forState:UIControlStateNormal];
    }else{
        [self.optionBtn setTitle:@"退出家庭" forState:UIControlStateNormal];
    }
    
    self.optionBtn.layer.cornerRadius = 5;
    self.optionBtn.backgroundColor = [UIColor whiteColor];
    self.optionBtn.layer.borderWidth = 1;
    self.optionBtn.layer.borderColor = rgba(151, 151, 151).CGColor;
    
}

-(void)rightFunc:(id)sender{
    TYMWeak(self);
    [AddFamilyView showAddFamilyActionCompletion:^(NSInteger actionType) {
        [weakself actionViewWithType:actionType];
    }];
}

-(void)actionViewWithType:(NSInteger)type{
    
    if (type == 1) {
        CreateNewHomeViewController *createVC = [[CreateNewHomeViewController alloc] init];
        [self.navigationController pushViewController:createVC animated:YES];
    }else{
        JoinHomeViewController *joinVC = [[JoinHomeViewController alloc] init];
        [self.navigationController pushViewController:joinVC animated:YES];
    }
}

-(void)backViewFunc:(id)btn{
   if (self.navigationController.viewControllers.count>1) {
        [super backViewFunc:btn];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    [self getCurrentUserFamilyWithWeb];
    [self getOneArrayWithWeb];
    [self getFamilyUsersWithWeb];
}

-(void)deleteFamily{
    [self.familyService getExitfamilyWithFamilyID:[UserTool getCurrentFamily].familyId Completion:^(LMJBaseResponse *responsed) {
        if (responsed.code == 0) {
               [UserTool clearFamilycompletion:^(BOOL state) {
                   if(state){
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"showLoginView" object:@(1)];
                   }
               }];
           }else{
               [WHToast showMessage:responsed.message duration:2 finishHandler:nil];
           }
       }];
}

-(IBAction)deleteGoOutFamily:(id)sender{
    
    TYMWeak(self);
    [ShowAlertView showAlertViewTitle:@"提示" message:@"确定删除并退出该家庭吗?" actionBtnTitle:@"确定"
                           hiddenCancel:NO
                           completion:^(NSInteger actionType) {
        if (actionType) {
            [weakself deleteFamily];
        }
    }];
}

-(FamilyService*)familyService{
    if (_familyService == nil) {
        _familyService = [[FamilyService alloc] init];
    }
    return _familyService;
}

-(NSMutableArray*)oneArray{
    if (_oneArray == nil) {
        _oneArray = [[NSMutableArray alloc] init];
    }
    return _oneArray;
}

-(void)setTwoArray{
    if([UserTool getLogInUser]){
        _twoArray = [[NSMutableArray alloc] initWithArray: @[@{@"title":@"我的身份",@"con":[UserTool getCurrentFamily].getRoleStr,@"isShowRight":@(0)},
                                                             @{@"title":@"家庭切换",@"con":[UserTool getCurrentFamily].familyName?[UserTool getCurrentFamily].familyName:@"",@"isShowRight":@(1)},
                                                             @{@"title":@"黑名单用户",@"con":@"",@"isShowRight":@(1)},
                                                             @{@"title":@"家庭头像",@"con":[UserTool getCurrentFamily].image,@"isShowRight":[UserTool getCurrentFamily].familyRole==1?@(1): @(0)},
                                                             @{@"title":@"家庭名称",@"con":[UserTool getCurrentFamily].familyName,@"isShowRight":[UserTool getCurrentFamily].familyRole==1?@(1): @(0)},
                                                             @{@"title":@"家庭描述",@"con":[UserTool getCurrentFamily].familyDesc,@"isShowRight":[UserTool getCurrentFamily].familyRole==1?@(1): @(0)}]];
        if ([UserTool getCurrentFamily].familyRole == 2) {
            [self.twoArray removeObjectAtIndex:2];
        }
    }
    
}

-(NSMutableArray*)threeArray{
    if (_threeArray == nil) {
        _threeArray = [[NSMutableArray alloc] init];
    }
    return _threeArray;
}

-(void)getCurrentUserFamilyWithWeb{
    [self.familyService getFamilyUserCurrentCompletion:^(LMJBaseResponse *respns, FamilyModel * _Nonnull response) {
        if (!respns.code) {
            [UserTool setFamily:response completion:^(BOOL state) {
                if(state){
                                   [self setTwoArray];
                                }
                }];
        }
    }];
}

-(void)getOneArrayWithWeb{
    //家长
    if ([UserTool getCurrentFamily].familyRole == 1) {
        [self getFamilyFpplysWithFamilyId];
    }else{
        if (self.oneArray.count) {
            [self.oneArray removeAllObjects];
        }
        [self getFinduserApplyscompletion];
    }
}

//获取用户申请加入的
-(void)getFamilyFpplysWithFamilyId{
    TYMWeak(self);
    [self.familyService getFamilyFpplysWithFamilyId:[UserTool getCurrentFamily].familyId completion:^(NSError * _Nonnull error, NSArray<ApplyforModel *> * _Nonnull array) {
        if (weakself.oneArray.count) {
            [weakself.oneArray removeAllObjects];
        }
        [weakself.oneArray addObjectsFromArray:array];
        [weakself getFinduserApplyscompletion];
    }];
}

//获取我申请加入的
-(void)getFinduserApplyscompletion{
    
    TYMWeak(self);
    [self.familyService getFinduserApplyscompletion:^(NSError * _Nonnull error, NSArray<ApplyforModel *> * _Nonnull array) {
        [weakself.oneArray addObjectsFromArray:array];
        [weakself.tableView reloadData];
    }];
}

-(void)getFamilyUsersWithWeb{
    TYMWeak(self);
    [self.familyService getFamilyuserfindfamilyusers:[UserTool getCurrentFamily].familyId status:1 type:3 completion:^(NSError * _Nonnull error, NSArray<UserModel *> * _Nonnull array) {
        if (weakself.threeArray.count) {
            weakself.threeIndex = 0;
            [weakself.threeArray removeAllObjects];
        }
        for (int i=0;i<array.count;i++) {
            UserModel *model = array[i];
            if (model.type == 2 &&  weakself.threeIndex == 0) {
                weakself.threeIndex = i;
            }
            [weakself.threeArray addObject:model];
        }
        [weakself.tableView reloadData];
    }];
}

//取消自己的申请
-(void)opationCancelApply{
    if (!self.oneArray.count) {
        return;
    }
    TYMWeak(self);
    ApplyforModel *applyModel = self.oneArray[self.optionRow];
    [self.familyService getFamilyuserCancelapplyApplyId:applyModel.applyid completion:^(NSError * _Nonnull error, id  _Nonnull responObjec) {
        if (!error) {
            [WHToast showMessage:@"取消申请成功" duration:2 finishHandler:nil];
            [weakself.oneArray removeObjectAtIndex:weakself.optionRow];
            [weakself.tableView reloadData];
        }
    }];
}

//0:同意 1:拒绝 2:加入黑名单
-(void)optionActionApplyIdWithOptionType:(NSInteger)type{
    if (!self.oneArray.count) {
        return;
    }
    ApplyforModel *applyModel = self.oneArray[self.optionRow];
    TYMWeak(self);
    [self.familyService getFamilyuserAuditapplyId:applyModel.applyid status:type auditDesc:@"" completion:^(NSError * _Nonnull error, id  _Nonnull responObjec) {
        if (!error) {
            [WHToast showMessage:@"操作成功" duration:2 finishHandler:^{
                [weakself viewWillAppear:nil];
            }];
        }
    }];
    
}

#pragma mark delegate datasource
- (NSInteger)numberOfSectionsInGroupShadowTableView:(GroupShadowTableView *)tableView {
    return 3;
}

- (NSInteger)groupShadowTableView:(GroupShadowTableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.oneArray.count;
    }else if (section == 1) {
        return  self.twoArray.count;
    }else if(section == 2){
        return  self.threeArray.count;
    }
    return 3;
}

- (CGFloat)groupShadowTableView:(GroupShadowTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            return [FamilyManageOneCell cellForHeight]+54;
        }else if(indexPath.row == _oneArray.count-1){
            return [FamilyManageOneCell cellForHeight]+10;
        }
        return [FamilyManageOneCell cellForHeight];
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            return [FamilyManageTwoCell cellForHeight]+54;
        }else if(indexPath.row == _twoArray.count-1){
            return [FamilyManageTwoCell cellForHeight]+10;
        }
        return [FamilyManageTwoCell cellForHeight];
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            return [FamilyManageThreeCell cellForHeight]+54;
        }else if(indexPath.row == _threeArray.count-1){
            return [FamilyManageThreeCell cellForHeight]+10;
        }
        return [FamilyManageThreeCell cellForHeight];
    }
    return 0;
}

- (UITableViewCell *)groupShadowTableView:(GroupShadowTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section==0) {
        FamilyManageOneCell *cell = [tableView dequeueReusableCellWithIdentifier:[FamilyManageOneCell identifier]];
        if (!cell) {
            cell = [[FamilyManageOneCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:[FamilyManageOneCell identifier]];
        }
        if (indexPath.row == 0) {
            [cell showSectionView];
        }else{
            [cell hiddenSectionView];
        }
        cell.model = _oneArray[indexPath.row];
        TYMWeak(self);
        cell.optionBlock = ^(NSInteger  applyId) {
            weakself.optionRow = indexPath.row;
            if (weakself.oneArray.count) {
                ApplyforModel *model = weakself.oneArray[indexPath.row];
                if (![[UserTool getLogInUser].mobile isEqualToString:model.mobile]) {
                    [FamilyOptionView showOptionViewCompletion:^(NSInteger otionType) {
                        
                        [weakself optionActionApplyIdWithOptionType:otionType];
                    }];
                }else{
                    [ShowAlertView showAlertViewTitle:@"提示" message:@"确定取消申请吗？" actionBtnTitle:@"确定"
                                           hiddenCancel:NO
                                           completion:^(NSInteger actionType) {
                        if (actionType) {
                        [weakself opationCancelApply];
                        }
                    }];
                }
            }
        };
        return cell;
    }else if(indexPath.section == 1){
        FamilyManageTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:[FamilyManageTwoCell identifier]];
        if (!cell) {
            cell = [[FamilyManageTwoCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:[FamilyManageTwoCell identifier]];
        }
        if (indexPath.row == 0) {
            [cell showSectionView];
        }else{
            [cell hiddenSectionView];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        NSDictionary *dic = _twoArray[indexPath.row];
        cell.titLab.text = dic[@"title"];
        cell.conLab.text = dic[@"con"];
        [cell setRightImageIshiden:[dic[@"isShowRight"] integerValue]];
        
        if ([cell.titLab.text isEqualToString:@"家庭头像"]) {
            cell.conLab.hidden = YES;
            [cell.headImage yp_setImageUlr: [NSString stringWithFormat:@"%@%@",BaseImageUrl,dic[@"con"]]];
        }else{
            cell.conLab.hidden = NO;
        }
        
        return cell;
    }else if(indexPath.section == 2){
        FamilyManageThreeCell *cell = [tableView dequeueReusableCellWithIdentifier:[FamilyManageTwoCell identifier]];
        if (!cell) {
            cell = [[FamilyManageThreeCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:[FamilyManageThreeCell identifier]];
        }
        if (indexPath.row == 0) {
            [cell showSectionView];
        }else{
            [cell hiddenSectionView];
        }
        
        cell.userModel = self.threeArray[indexPath.row];
        
        if (indexPath.row == self.threeIndex && self.threeIndex > 0) {
            cell.lineV.hidden = NO;
        }
        return cell;
    }
    
    return [[UITableViewCell alloc] initWithFrame:CGRectZero];
}

-(void)groupShadowTableView:(GroupShadowTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            ChangeFamilyVC *changVC = [[ChangeFamilyVC alloc] init];
            [self.navigationController pushViewController:changVC animated:YES];
        }
        //家长可以访问
        if ([UserTool getCurrentFamily].familyRole == 1) {
            
            if(indexPath.row == 2){
                BlacklistVC *blackVC = [[BlacklistVC alloc] init];
                [self.navigationController pushViewController:blackVC animated:YES];
            }else if(indexPath.row == 3){
               
                self.manager.type  = HXPhotoManagerSelectedTypePhoto;
                self.manager.configuration.openCamera = YES;
                YPVideoPickerViewController *vc = [[YPVideoPickerViewController alloc] init];
                 vc.manager = self.manager;
                 vc.delegate = self;
                [self.navigationController pushViewController:vc animated:YES];
            }else if(indexPath.row == 4){
                FamilyNameVC *nameVC = [[FamilyNameVC alloc] init];
                nameVC.familymodel = [UserTool getCurrentFamily];
                [self.navigationController pushViewController:nameVC animated:YES];
            }else if(indexPath.row == 5){
                FamilyDescVC *descVC = [[FamilyDescVC alloc]  init];
                descVC.familymodel = [UserTool getCurrentFamily];
                [self.navigationController pushViewController:descVC animated:YES];
            }
            
        }
    }else if(indexPath.section == 2){
        
        UserModel *model= _threeArray[indexPath.row];
        if(model.type == 1){ //app用户
            FamilymemberVC *memberVC = [[FamilymemberVC alloc] init];
            memberVC.userModel = _threeArray[indexPath.row];
            [self.navigationController pushViewController:memberVC animated:YES];
        }else{
            
            YoukeUserVC *youkeVC = [[YoukeUserVC alloc] initWithUserModel:model];
            [self.navigationController pushViewController:youkeVC animated:YES];
        }
        
        
    }
    
}


#pragma mark - 懒加载选择视频的manager
- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
        _manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;
        _manager.configuration.openCamera = NO;
        _manager.configuration.videoMaxNum = 1;
        _manager.configuration.maxNum = 1;
        _manager.configuration.photoCanEdit = NO;
        _manager.configuration.hideOriginalBtn = YES;
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.replacePhotoEditViewController = NO;
        _manager.configuration.replaceVideoEditViewController = NO;
        _manager.configuration.showBottomPhotoDetail = NO;
        _manager.configuration.themeColor = [UIColor blackColor];
        _manager.configuration.navBarBackgroudColor = [UIColor blackColor];
        _manager.configuration.navigationTitleColor = [UIColor whiteColor];
        _manager.configuration.selectVideoLimitSize = YES;
        _manager.configuration.limitVideoSize = 1024*1024*100;
        _manager.configuration.photoStyle = HXPhotoStyleDark;
        _manager.configuration.cellDarkSelectBgColor = rgba(76, 132, 255);
        _manager.configuration.languageType = HXPhotoLanguageTypeSc;
        _manager.configuration.reverseDate = YES;
        _manager.configuration.videoMaximumSelectDuration = 60;
    }
    return _manager;
}

#pragma mark - HXPhotoViewController delegate
- (void)photoViewController:(HXPhotoViewController *)photoViewController
didDoneAllList:(NSArray<HXPhotoModel *> *)allList
        photos:(NSArray<HXPhotoModel *> *)photoList
        videos:(NSArray<HXPhotoModel *> *)videoList
                   original:(BOOL)original{
    if (photoList.count > 0) {
       HXPhotoModel *photoModel = photoList.firstObject;
        //self.headImage.image = photoModel.thumbPhoto;
        [self personalUploadHeadImgInterfaceWithImage:photoModel.thumbPhoto];
    }
}

- (void)personalUploadHeadImgInterfaceWithImage:(UIImage *)uploadImage  {
    //网络请求管理器
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@", BaseUrl,  urlImageUpload];
    [sessionManager POST:requestUrlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@%@.jpg", [UserTool getLogInUser].token, str];
        [formData appendPartWithFileData:imageData name:@"file"  fileName:fileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (![responseObject[@"code"] integerValue]) {
            
            [self changeFamilyImage:responseObject[@"data"]];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WHToast showMessage:@"上传图片失败" duration:2 finishHandler:nil];
    }];
}

-(void)changeFamilyImage:(NSString*)imageUrl{
    TYMWeak(self);
    [self.familyService getUpdateFamilyWithFamilyId:[UserTool getCurrentFamily].familyId FamilyName:[UserTool getCurrentFamily].familyName desc:[UserTool getCurrentFamily].familyDesc image:imageUrl completion:^(LMJBaseResponse *response) {
           if (response.message) {
               [WHToast showMessage:response.message duration:2 finishHandler:nil];
           }else{
               [WHToast showMessage:@"修改成功" duration:2 finishHandler:nil];
               [weakself  getCurrentUserFamilyWithWeb];
               [weakself getOneArrayWithWeb];
               [weakself getFamilyUsersWithWeb];
           }
       }];
}

@end
